package com.zjp.aop.core;

import com.alibaba.ttl.TransmittableThreadLocal;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

public class LogContext {


    // 上下文

    //static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<>();

    // 支持子线程获取 父线程的变量
    // 父子线程共享变量
    private static final ThreadLocal<Stack<Map<String, Object>>> variableMapStack = new TransmittableThreadLocal<>();


    public static void setCurrentVariableMap() {
        Stack<Map<String, Object>> stackLocalMap = getStackLocalMap();
        stackLocalMap.push(new HashMap<>());
    }

    public static void removeCurrentVariableMap() {
        Stack<Map<String, Object>> stackLocalMap = getStackLocalMap();
        stackLocalMap.pop();
    }

    public static Map<String, Object> getCurrentVariableMap() {
        Stack<Map<String, Object>> stackLocalMap = getStackLocalMap();
        return stackLocalMap.lastElement();
    }


    public static Stack<Map<String, Object>> getStackLocalMap() {
        Stack<Map<String, Object>> mapStack = variableMapStack.get();
        if (mapStack == null) {
            mapStack = new Stack<>();
            variableMapStack.set(mapStack);
        }
        return mapStack;
    }


    public static void  putVariable(String name,Object o){
        Map<String, Object> currentVariableMap = getCurrentVariableMap();
        currentVariableMap.put(name, o);
    }





    /*public static void putVariable(String name, Object o) {
        Map<String, Object> map = threadLocal.get();
        if (Objects.isNull(map)) {
            map = new HashMap<>();
            threadLocal.set(map);
        }
        map.putIfAbsent(name, o);
    }


    public static Map<String, Object> getData() {
        Map<String, Object> map = threadLocal.get();
        if (Objects.isNull(map)) {
            map = new HashMap<>();
            threadLocal.set(map);
        }
        return map;
    }


    public static void remove() {
        threadLocal.remove();
    }

    public void init() {
        Map<String, Object> map = threadLocal.get();
        if (Objects.isNull(map)) {
            threadLocal.set(new HashMap<>());
        }
    }*/

}
